﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace HgAdapter
{
	public class HgStatus : HgCommand
	{
		public Dictionary<string, VersionStatus> Run()
		{
			string output = GetHgStatusOutput();
			return ParseOutput(output);
		}

		private static Dictionary<string, VersionStatus> ParseOutput(string output)
		{
			Dictionary<string, VersionStatus> result = new Dictionary<string, VersionStatus>();
			
			string[] outputStrings = output.Split('\n');
			foreach (string outputString in outputStrings)
			{
				if (outputString.IndexOf(' ') == 1)
				{
					string fullFileName = Path.Combine(
						ProjectCommitInfo.Instance.ProjectPath, 
						outputString.Substring(2));
					VersionStatus versionStatus = GetVersionStatus(outputString.Substring(0, 1));

					result[fullFileName] = versionStatus;
				}
			}
			return result;
		}

		private static VersionStatus GetVersionStatus(string statusLetter)
		{
			if (statusLetter == "A")
				return VersionStatus.Added;
			if (statusLetter == "C")
				return VersionStatus.Unchanged;
			if (statusLetter == "M")
				return VersionStatus.Changed;
			if (statusLetter == "?")
				return VersionStatus.Unversioned;
			if (statusLetter == "!")
				return VersionStatus.Missed;
			return VersionStatus.Empty;
		}

		private static string GetHgStatusOutput()
		{
			string result;

			string saveCurrentDirectory = Environment.CurrentDirectory;
			Environment.CurrentDirectory = ProjectCommitInfo.Instance.ProjectPath;

			Process hgProcess = Process.Start(HgStatusStartInfo("status -A"));
			hgProcess.WaitForExit(1000);
			result = hgProcess.StandardOutput.ReadToEnd();

			Environment.CurrentDirectory = saveCurrentDirectory;

			return result;
		}


	}
}
